<script>
  import KnowledgeConfig from "$lib/components/KnowledgeConfig.svelte";
  import { onMount } from 'svelte';
  
  let knowledgeData = [];
  let loading = false;
  let error = null;
  
  // 模拟从API获取知识配置数据
  async function fetchKnowledgeData() {
    loading = true;
    error = null;
    
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 模拟API返回的知识配置数据
      knowledgeData = [
        {
          id: 1,
          name: "零售金融",
          knowledgeName: "零售金融",
          ragflowIds: ["adbsadasd213123", "21312edafafas"],
          searchKeyword: "启用调度间答知识库的时候要求！当状内容时中存在不同年份的不...",
          apiKey: "ajgcqa-Aynf123124dada",
          citationUrl: "",
          thirdPartyWhitelist: false,
          userWhitelist: false,
          departmentWhitelist: false,
          maxBlocks: 15,
          relevanceThreshold: 0.8,
          weightSort: 0.8,
          thirdPartyUsers: [],
          userWhitelistUsers: [],
          departmentWhitelistDepts: []
        },
        {
          id: 2,
          name: "技术文档",
          knowledgeName: "技术文档",
          ragflowIds: ["tech001", "tech002"],
          searchKeyword: "技术文档相关的搜索关键字...",
          apiKey: "tech-api-key-123",
          citationUrl: "https://tech.example.com",
          thirdPartyWhitelist: true,
          userWhitelist: true,
          departmentWhitelist: true,
          maxBlocks: 20,
          relevanceThreshold: 0.7,
          weightSort: 0.6,
          thirdPartyUsers: ["system001", "system002"],
          userWhitelistUsers: ["user001", "user002"],
          departmentWhitelistDepts: ["it", "development"]
        }
      ];
    } catch (err) {
      console.error('获取知识配置数据失败:', err);
      error = '数据加载失败，请稍后重试';
      knowledgeData = [];
    } finally {
      loading = false;
    }
  }
  
  // 组件挂载时获取数据
  onMount(() => {
    fetchKnowledgeData();
  });
  
  // 重新加载数据
  function handleRefresh() {
    fetchKnowledgeData();
  }
</script>

<div class="knowledge-config-page">
  <div class="page-header">
    <h1>知识配置管理</h1>
    <button class="refresh-btn" on:click={handleRefresh} disabled={loading}>
      {#if loading}
        🔄 加载中...
      {:else}
        🔄 刷新数据
      {/if}
    </button>
  </div>
  
  {#if loading}
    <div class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载知识配置数据...</p>
    </div>
  {:else if error}
    <div class="error-container">
      <div class="error-message">
        <span class="error-icon">⚠️</span>
        <span>{error}</span>
      </div>
      <button class="retry-btn" on:click={handleRefresh}>
        重新加载
      </button>
    </div>
  {:else}
    <KnowledgeConfig bind:data={knowledgeData} />
  {/if}
</div>
